// API基础URL配置
const API_BASE_URL = 'http://localhost:5003';

// 检查并更新用户登录状态
async function updateUserLoginStatus() {
    const userInfoDiv = document.querySelector('.user-info');
    const authButtons = document.querySelector('.auth-buttons');
    const usernameDisplay = document.getElementById('username-display');

    // 获取最新的用户信息
    const userProfile = await fetchUserProfile();
    
    if (userProfile) {
        userInfoDiv.style.display = 'block';
        authButtons.style.display = 'none';
        usernameDisplay.textContent = userProfile.username;
    } else {
        userInfoDiv.style.display = 'none';
        authButtons.style.display = 'block';
    }
}

// 获取用户信息的函数
async function fetchUserProfile() {
    try {
        const token = localStorage.getItem('token');
        if (!token) return null;

        const response = await fetch(`${API_BASE_URL}/user/profile`, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            }
        });

        const data = await response.json();
        if (data.code === 200) {
            return data.data;
        } else {
            console.error('获取用户信息失败:', data.message);
            return null;
        }
    } catch (error) {
        console.error('获取用户信息出错:', error);
        return null;
    }
}

// 退出登录处理函数
function handleLogout() {
    if (confirm('确定要退出登录吗？')) {
        localStorage.removeItem('token');
        localStorage.removeItem('user');

        const modal = document.getElementById('user-modal');
        if (modal) {
            modal.style.display = 'none';
        }

        showMessage('已成功退出登录');
        
        // 更新界面显示
        const userInfoDiv = document.querySelector('.user-info');
        const authButtons = document.querySelector('.auth-buttons');
        
        userInfoDiv.style.display = 'none';
        authButtons.style.display = 'block';

        window.location.href = 'index.html';
    }
}

// 消息提示函数
function showMessage(message) {
    const messageDiv = document.createElement('div');
    messageDiv.className = 'message-toast';
    messageDiv.textContent = message;
    document.body.appendChild(messageDiv);

    setTimeout(() => messageDiv.classList.add('show'), 10);

    setTimeout(() => {
        messageDiv.classList.remove('show');
        setTimeout(() => messageDiv.remove(), 300);
    }, 3000);
}

// 页面加载时执行
document.addEventListener('DOMContentLoaded', function() {
    // 更新用户登录状态
    updateUserLoginStatus();

    // 设置用户详情模态窗口事件
    const usernameDisplay = document.getElementById('username-display');
    if (usernameDisplay) {
        usernameDisplay.onclick = async function() {
            const userProfile = await fetchUserProfile();
            if (userProfile) {
                const userModal = document.getElementById('user-modal');
                document.getElementById('modal-username').textContent = userProfile.username;
                document.getElementById('modal-email').textContent = userProfile.email;
                document.getElementById('modal-userid').textContent = userProfile.user_id;
                userModal.style.display = 'block';
            } else {
                localStorage.removeItem('token');
                localStorage.removeItem('user');
                window.location.href = 'auth.html#login';
            }
        }
    }

    // 设置模态窗口关闭事件
    const closeButton = document.querySelector('.close-button');
    if (closeButton) {
        closeButton.onclick = function() {
            document.getElementById('user-modal').style.display = 'none';
        }
    }

    // 点击模态窗口外部关闭
    window.onclick = function(event) {
        const modal = document.getElementById('user-modal');
        if (event.target == modal) {
            modal.style.display = 'none';
        }
    }
});